﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using CUWo.App.CustomControl;
using CUWo.App.Resources;
using CUWo.Common;
using CUWo.Common.Entities;
using CUWo.Common.Entities.WoInterface.HttpJsonResult;
using CUWo.Common.StorageHelper;
using CUWo.Common.WebHelper;
using CUWo.Common.WoInterfaceCommunication;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace CUWo.App.Views
{
    public partial class PageUserCenter : PhoneApplicationPage
    {
        public PageUserCenter()
        {
            InitializeComponent();

            this.woucConfig.OnWriteSuggestTap += woucConfig_OnWriteSuggestTap;
            this.woucConfig.OnSuggestListTab += woucConfig_OnSuggestListTab;

        }





        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (!base.NavigationContext.QueryString.ContainsKey("pivotitem"))
            {
                return;
            }

            string pivotItemName = base.NavigationContext.QueryString["pivotitem"];
            if (string.IsNullOrWhiteSpace(pivotItemName))
                return;

            switch (pivotItemName)
            {
                case "pivotEmail": this.pivot.SelectedItem = this.pivotEmail; break;
                case "pivotMessage": this.pivot.SelectedItem = this.pivotMessage; break;
                case "pivotUpdatePassword": this.pivot.SelectedItem = this.pivotUpdatePassword; break;
                case "pivotRegister": this.pivot.SelectedItem = this.pivotRegister; break;
                case "pivotLogin": this.pivot.SelectedItem = this.pivotLogin; break;
                case "pivotSetting":
                default:
                    break;
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            //
            if (this.pivotSetting == this.pivot.SelectedItem)
            {
                if (this.woucConfig.gridSettingSuggestList.Visibility == Visibility.Collapsed)
                {
                    ApplicationBar = ((ApplicationBar)this.Resources["appBarFeedbackList"]);
                    ApplicationBar.IsVisible = true;
                    this.woucConfig.gridSettingSuggestList.Visibility = Visibility.Visible;
                    this.woucConfig.gridSettingSuggestWrite.Visibility = Visibility.Collapsed;
                    e.Cancel = true;
                }
                else if (this.woucConfig.gridSettingMain.Visibility == Visibility.Collapsed)
                {
                    ApplicationBar = new ApplicationBar();
                    ApplicationBar.IsVisible = false;
                    this.woucConfig.gridSettingMain.Visibility = System.Windows.Visibility.Visible;
                    this.woucConfig.gridSettingAbout.Visibility = System.Windows.Visibility.Collapsed;
                    this.woucConfig.gridSettingSuggest.Visibility = System.Windows.Visibility.Collapsed;
                    this.woucConfig.gridSettingQA.Visibility = System.Windows.Visibility.Collapsed;
                    e.Cancel = true;
                }


            }
            //


        }



        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.IsVisible = false;

            if (this.pivotRegister == this.pivot.SelectedItem)
            {
                LoadRomInfo();
                ApplicationBar = ((ApplicationBar)this.Resources["appBarRegister"]);
            }
            else if (this.pivotLogin == this.pivot.SelectedItem)
            {
                LoadRomInfo();
                ApplicationBar = ((ApplicationBar)this.Resources["appBarLogin"]);
            }
            else if (this.pivotUpdatePassword == this.pivot.SelectedItem)
            {
                LoadRomInfo();
                ApplicationBar = ((ApplicationBar)this.Resources["appBarUpdatePassword"]);
            }
            else if (this.pivotEmail == this.pivot.SelectedItem)
            {  
                this.woucEmail.IsEnabledWoEmail();
            }
            else if (this.pivotSetting == this.pivot.SelectedItem)
            {  
                if (this.woucConfig.gridSettingSuggest.Visibility == System.Windows.Visibility.Visible)
                {
                    if (this.woucConfig.gridSettingSuggestList.Visibility == Visibility.Visible)
                    {
                        ApplicationBar = ((ApplicationBar)this.Resources["appBarFeedbackList"]);
                        ApplicationBar.IsVisible = true;
                    }
                    else if (this.woucConfig.gridSettingSuggestWrite.Visibility == Visibility.Visible)
                    {
                        ApplicationBar = ((ApplicationBar)this.Resources["appBarSubmitFeedback"]);
                        ApplicationBar.IsVisible = true;
                    }
                }
            }
            else
            {
                ApplicationBar = new ApplicationBar();
                ApplicationBar.IsVisible = false;
            }
        }

        private void appBarRegister_Click(object sender, EventArgs e)
        {
            this.Focus();
            this.woucRegister.MobileRegister();
        }

        private void appBarConfirm_Click(object sender, EventArgs e)
        {
            this.Focus();
            this.woucLogin.MobileLoginOrForgetPassword();
        }

        private void appBarUpdatePassword_Click(object sender, EventArgs e)
        {
            this.Focus();
            this.woucUpdatePassword.UpdatePassword();
        }


        void LoadRomInfo()
        {
            this.woucRegister.txtMobile.Text = AppResources.UserCenterRegisterInputChinaUnicomMobile;
            this.woucLogin.txtMobile.Text = AppResources.UserCenterRegisterInputChinaUnicomMobile;
            this.woucLogin.txtConfirmMobile.Text = AppResources.UserCenterRegisterInputChinaUnicomMobile;
            this.woucUpdatePassword.txtMobile.Text = AppResources.UserCenterRegisterInputChinaUnicomMobile;

            if (!IsolatedStorageHelper.Instance.FileExists(Keys.ROM_FILENAME))
            {
                return;
            }
            var romInfoString = IsolatedStorageHelper.Instance.ReadText(Keys.ROM_FILENAME);
            if (!string.IsNullOrWhiteSpace(romInfoString))
            {
                RomInfo romInfo = JSONHelper.Deserialize<RomInfo>(romInfoString);
                if (romInfo != null)
                {
                    if (!string.IsNullOrWhiteSpace(romInfo.Mobile))
                    {
                        this.woucRegister.txtMobile.Text = romInfo.Mobile;
                        this.woucLogin.txtMobile.Text = romInfo.Mobile;
                        this.woucLogin.txtConfirmMobile.Text = romInfo.Mobile;
                        this.woucUpdatePassword.txtMobile.Text = romInfo.Mobile;
                        TextBlock content = this.woucConfig.FindVisualChild(this.woucConfig.tgsPush, "txtToggleSwitchStatus");
                        if (content != null)
                        {
                            content.Text = romInfo.IsPush ? "开启" : "关闭";
                        }
                    }
                }
            }
        }

        #region 撰写反馈意见
        void woucConfig_OnSuggestListTab(object sender, EventArgs e)
        {
            ApplicationBar = ((ApplicationBar)this.Resources["appBarFeedbackList"]);
        }

        void woucConfig_OnWriteSuggestTap(object sender, EventArgs e)
        {

        }
        private void appBarWriteFeedback_Click(object sender, EventArgs e)
        {
            this.woucConfig.gridSettingSuggestWrite.Visibility = Visibility.Visible;
            this.woucConfig.gridSettingSuggestList.Visibility = Visibility.Collapsed;
            ApplicationBar = ((ApplicationBar)this.Resources["appBarSubmitFeedback"]);
        }

        /// <summary>
        /// 提交反馈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarSubmitFeedback_Click(object sender, EventArgs e)
        {
            //TODO 反馈接口中没有提交联系方式的字段？
            //TODO 反馈接口中的IEMI长度必须是15，在Windows Phone中没有IMEI，只有与应用对应的唯一设备号
            string content = this.woucConfig.txtFeedbackContent.Text.Trim();
            string contract = this.woucConfig.txtFeedbackContract.Text.Trim();
            if (string.IsNullOrWhiteSpace(content) || AppResources.UserCenterConfigInputFeedbackContent.Equals(content))
            {
                MessageToastManager.Show(AppResources.UserCenterConfigInputFeedbackContent);
                return;
            }

            string mobileNumber = string.Empty;
            if (string.IsNullOrWhiteSpace(contract) || AppResources.UserCenterConfigInputFeedbackContract.Equals(contract))
            {
                RomInfo romInfo = RomHelper.GetRomInfo();
                if (romInfo != null)
                {
                    mobileNumber = romInfo.Mobile;
                    contract = mobileNumber;
                }
            }
            if (string.IsNullOrWhiteSpace(mobileNumber))
            {
                MessageToastManager.Show("未登录！");
                return;
            }

            //获取请求地址
            string requestUrl = new CUWo.Common.WoInterfaceCommunication.SubmitFeedback().GetUrl(mobileNumber, content);
            LogHelper.LogInfo(requestUrl);
            //

            PopupProgressBar.OpenProgressBar();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);
                        PopupProgressBar.CloseProgressBar();

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        JsonResultRootJsonCharacterString rootCharacterString = JSONHelper.Deserialize<JsonResultRootJsonCharacterString>(result);
                        if (rootCharacterString == null)
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            AESHelper aesHelper = new AESHelper(AESHelper.KeySize.Bits128, AESHelper.Hex2Byte(new CommunicationBase().CHANNEL_PASSWORD));
                            byte[] decryptByteResult = aesHelper.InvCipher(AESHelper.Hex2Byte(rootCharacterString.RootValue));
                            string decryptStringResult = Encoding.UTF8.GetString(decryptByteResult, 0, decryptByteResult.Length);
                            LogHelper.LogInfo("Decrypt:\t" + decryptStringResult);
                            JsonResultRootMsgCharacterString jsonResult = JSONHelper.Deserialize<JsonResultRootMsgCharacterString>(decryptStringResult);
                            if (jsonResult != null)
                            {
                                if (jsonResult.Message != null)
                                {
                                    if (jsonResult.Message.MessageErrors != null && jsonResult.Message.MessageErrors.Count > 0)
                                    {
                                        MessageToastManager.Show(jsonResult.Message.MessageErrors[0].MessageContent, MessageToastLevel.Error);
                                        //有错误
                                    }
                                    else if (jsonResult.Message.MessageWarns != null && jsonResult.Message.MessageWarns.Count > 0)
                                    {
                                        MessageToastManager.Show(jsonResult.Message.MessageWarns[0].MessageContent, MessageToastLevel.Warn);
                                    }
                                    else
                                    {
                                        //成功
                                        if (jsonResult.Message.MessagePrompts != null && jsonResult.Message.MessagePrompts.Count > 0)
                                        {
                                            MessageToastManager.Show("提交成功！");
                                        }
                                    }
                                }
                            }
                        }
                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {
                    PopupProgressBar.CloseProgressBar();
                    MessageToastManager.Show(err.Message);
                }
            }, webTask);

        }
        #endregion 撰写反馈意见


    }
}